import { ref } from 'vue';
import { message } from 'ant-design-vue';
import xxlJobApi from '../utils/xxlJobApi';

export function useScheduledTask() {
  const loading = ref(false);
  const taskResult = ref<any>(null);

  /**
   * 执行定时任务
   * @param taskId 任务ID，可选，如果不传则自动查找
   * @param jobGroup 任务组，默认为'5'
   * @param jobDesc 任务描述，默认为'处理委案和委案撤案的任务'
   * @returns Promise<boolean> 执行是否成功
   */
  const executeTask = async (
    taskId?: string | number, 
    jobGroup: string = '5', 
    jobDesc: string = '处理委案和委案撤案的任务'
  ): Promise<boolean> => {
    loading.value = true;
    taskResult.value = null;

    try {
      // 如果没有传入taskId，先获取任务列表找到对应的任务
      let finalTaskId: string | number | undefined = taskId;
      
      if (!finalTaskId) {
        const foundTaskId = await getTaskId(jobGroup, jobDesc);
        if (!foundTaskId) {
          message.error('未找到对应的任务');
          return false;
        }
        finalTaskId = foundTaskId;
      }
      
      // 执行任务
      const response = await xxlJobApi.post(
        '/jobinfo/trigger',
        `id=${finalTaskId}`
      );
      
      if (response.data && response.data.code === 200) {
        taskResult.value = response.data;
        message.success('任务执行成功');
        return true;
      } else {
        const errorMsg = response.data.msg || '未知错误';
        message.error('任务执行失败：' + errorMsg);
        return false;
      }
    } catch (error) {
      console.error('执行任务失败:', error);
      const errorMsg = error instanceof Error ? error.message : '执行任务失败，请稍后重试';
      message.error(errorMsg);
      return false;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 获取任务ID
   * @param jobGroup 任务组
   * @param jobDesc 任务描述
   * @returns Promise<string | null> 任务ID
   */
  const getTaskId = async (jobGroup: string, jobDesc: string): Promise<string | null> => {
    try {
    const response = await xxlJobApi.post(
      '/jobinfo/pageList',
      `jobGroup=${jobGroup}&triggerStatus=-1&jobDesc=${jobDesc}&executorHandler=&author=&start=0&length=100`
    );
      
      if (response.data && response.data.data && response.data.data.length > 0) {
        // 返回第一个匹配的任务ID
        return response.data.data[0].id;
      }
      
      return null;
    } catch (error) {
      console.error('获取任务列表失败:', error);
      return null;
    }
  };

  /**
   * 重置状态
   */
  const reset = () => {
    loading.value = false;
    taskResult.value = null;
  };

  return {
    loading,
    taskResult,
    executeTask,
    getTaskId,
    reset
  };
}
